package org.apache.lucene.ocean.util;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * DataInputStream extended to support VLong and VInt.  Also read strings
 * according to the default Lucene format.
 *
 */
public class VDataInputStream extends DataInputStream {
  private byte[] bytes;  // used by readString()
  
  public VDataInputStream(InputStream input) {
    super(input);
  }
  
  public String readString() throws IOException {
    int length = readVInt();
    if (bytes == null || length > bytes.length)
      bytes = new byte[(int) (length*1.25)];
    readFully(bytes, 0, length);
    return new String(bytes, 0, length, "UTF-8");
  }
  
  public long readVLong() throws IOException {
    byte b = readByte();
    long i = b & 0x7F;
    for (int shift = 7; (b & 0x80) != 0; shift += 7) {
      b = readByte();
      i |= (b & 0x7FL) << shift;
    }
    return i;
  }
  
  public int readVInt() throws IOException {
    byte b = readByte();
    int i = b & 0x7F;
    for (int shift = 7; (b & 0x80) != 0; shift += 7) {
      b = readByte();
      i |= (b & 0x7F) << shift;
    }
    return i;
  }
}
